<?php

/**
 * 收入确认信息仓库
 * @author zhoud 2018-02-02
 */
namespace common\repositories\myhtsq;

use common\repositories\BaseRepository;
use common\support\StringHelper;
use common\support\Helper;
use yii\db\Query;
use yii\web\ViewAction;
use common\entities\ConfigEntity;
use Exception;
use common\error\ErrorCode;
use common\entities\common\MyscrmRevenueRecognitionDateEntity;


class RevenueRecognitionDateRepository extends BaseRepository
{

    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    /**
     * 获取当前确认日期&上期确认日期
     * @return array
     */
    public static function getRecognitionDate()
    {
        return MyscrmRevenueRecognitionDateEntity::getRecognitionDate();
    }

    /**
     * 获取当前确认日期&上期确认日期
     * @return array
     */
    public static function getRecognitionDateNew()
    {
        return MyscrmRevenueRecognitionDateEntity::getRecognitionDateNew();
    }

    public static function getRecognitionListDate()
    {
        return MyscrmRevenueRecognitionDateEntity::getRecognitionListDate();
    }

    public static function getRecognitionListDateByTime($recognitionBegin,$recognitionEnd)
    {
        return MyscrmRevenueRecognitionDateEntity::getRecognitionListDateByTime($recognitionBegin,$recognitionEnd);
    }

    /**
     * 设置当前收入期
     * @param string $revenueId 收入ID
     * @param string $revenueId 收入ID
     * @return boolean|string 失败返回false，成功返回收入期Id
     */

    public static function setRecognitionDate($invoiceModel)
    {
        try {
            $entity = new MyscrmRevenueRecognitionDateEntity();
            $entity->setAttributes($invoiceModel->attributes);
            $entity->recognition_date_id = StringHelper::uuid();
            $entity->recognition_begin = self::formatDate($invoiceModel->recognition_begin);
            $entity->recognition_end = self::formatDate($invoiceModel->recognition_end);
            $entity->recognition_date = date('Y-m-d',MyscrmRevenueRecognitionDateEntity::getDbNowTimestamp());
            $entity->seter_guid = \Yii::$app->user->identity->userguid;
            $entity->set_by = \Yii::$app->session['__id'];
            $result = $entity->save();
            if ($result === FALSE) {
                return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL, $entity->firstErrorMessage);
            } else {
                return $entity->primaryKey;
            }
        } catch (Exception $ex) {
            return self::setAndReturn(ErrorCode::ERR_INVOICE_FORM_SAVE_FAIL, $ex->getMessage());
        }
    }

    private static function strtodate($date){
        return date("Y-m-d H:i:s",strtotime($date));
    }

    private static function dateToYmd($date){
        return substr($date, 0, -9);
    }

    private static function formatDate($date){
        return self::dateToYmd(self::strtodate($date));
    }

}